package com.sl.crawler.common.utils.encode;

import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.UnicodeDetector;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

public class FileEncoding {
    private static Logger log = LoggerFactory.getLogger(FileEncoding.class);

    public static String getFileCharacterEnding(String filePath) {
        String fileCharacterEnding = "UTF-8";
        CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
        //添加utf-8的支持
        detector.add(UnicodeDetector.getInstance());
        detector.add(JChardetFacade.getInstance());
//		detector.add(new ParsingDetector(false));
        Charset charset = null;
        File file = new File(filePath);
        try {
            charset = detector.detectCodepage(file.toURI().toURL());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (charset != null) {
            fileCharacterEnding = charset.name();
        }
        log.info("获取文件编码为" + fileCharacterEnding + filePath);
        //GB开头的GB2312 GBK升级为GB18030，支出繁体和生僻字
        if (StringUtils.startsWithAny(fileCharacterEnding.toUpperCase(), new String[]{"GB", "B"})) {
            fileCharacterEnding = "GB18030";
            log.info("修改文件编码为" + fileCharacterEnding + filePath);
        }
        // 韩文改为中文
        if (StringUtils.equals(fileCharacterEnding, "EUC-KR")) {
            fileCharacterEnding = "GB18030";
            log.info("修改文件编码为" + fileCharacterEnding + filePath);
        }

        return fileCharacterEnding;
    }

    public static void main(String[] args) {
        String filePath = "c:/test/online-afs_yewus.sql";
        String charset = getFileCharacterEnding(filePath);
        try {
            String sql = FileUtils.readFileToString(new File(filePath), charset);
            System.out.println(sql);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(charset);
    }
}
